package com.whoops.cloud.security.tool;

import com.whoops.cloud.security.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {
    public static final String  SUBJECT = "cloud";
    public static final Long EXPIRE = 1000*60*30L; //过期时间30分钟
    public static final String SECURITY = "whoops";//秘钥

    /**
     * 生成token
     */
    public static String createToken(User user){
        if (user == null || user.getUsername() == null){
            return null;
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                        .claim("username",user.getUsername())
                        .setIssuedAt(new Date())
                        .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                        .signWith(SignatureAlgorithm.HS256,SECURITY).compact();
        return token;
    }

    /**
     * 校验token
     */
    public static Claims checkToken(String token){
        try{
            Claims claims = Jwts.parser().setSigningKey(SECURITY)
                            .parseClaimsJws(token).getBody();
            return claims;
        }catch (Exception e){

        }
        return null;
    }

}
